package bupt.party.online.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import bupt.party.online.util.SessionConstants;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class AuthCheckInterceptor extends AbstractInterceptor{

	private static final long serialVersionUID = 1L;

	public String intercept(ActionInvocation invocation) throws Exception {
		
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		
		//通过"级别"可以判断这个用户是学生、管理员
		Integer level = (Integer) session.getAttribute(SessionConstants.LEVEL);
		ActionContext ctx = ActionContext.getContext();
		
		//wangdong
		Map<String, Object> params = invocation.getInvocationContext().getParameters();
		String[] categoryId = (String[])params.get("categoryId"); 
		String[] videopath = (String[]) params.get("videopath"); 
		if(categoryId != null && categoryId.length > 0 && videopath != null && videopath.length > 0) {
			ctx.put("categoryId", categoryId[0]);
			ctx.put("videopath", videopath[0]);
		}
		
		Object obj = ctx.getSession().get(SessionConstants.SESSION_USER);
		if(obj==null){
			
			//获得当前点击的actionName
			String uri = request.getRequestURI();
			
			if(uri!=null&&uri.endsWith(".action")){	
				//uri = uri.substring(1, uri.length()-7);
				String[] uriArray = uri.split("/");
				uri = uriArray[uriArray.length - 1];
			}
			
			
			if(!uri.contains("Admin")){//当登录的action名字不是以“Admin”开头的才会保存。
				session.setAttribute("actionName", uri);//保存的路径里面有了项目的名字。 如何去掉项目的名字呢
			}
			
			
			return "loginUI";
			
		}else{//判断是用户类别
			
			String serverPath = this.getServerPath();
			
			if(level==SessionConstants.STU_LEVEL){//学生
				if(!serverPath.contains("Admin")){
					return invocation.invoke();
				}else
					return "loginUI";
			}else if(level==SessionConstants.ADMIN_FIRST_LEVEL){//支部
				//获得action的开始是以admin开始的,那么要提示不能访问，或者提示登录。
				if(serverPath.contains("Admin")){
					return invocation.invoke();
				}else
					return "loginUI";
			}else if(level==SessionConstants.ADMIN_SECOND_LEVEL){//分党委
				if(serverPath.contains("Admin")){
					return invocation.invoke();
				}else
					return "loginUI";
			}else if(level==SessionConstants.ADMIN_THIRD_LEVEL){//校党委
				if(serverPath.contains("Admin")){
					return invocation.invoke();
				}else
					return "loginUI";
			}else{
				return "loginUI";
			}
		}
		
	}
	
	
	/**
	 * 获得请求的路径的开始的5个字母（“Admin”）
	 * @return
	 */
	public String getServerPath() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String serverPath = request.getRequestURI().replace(".action", "");
		//获得当前点击的actionName
		
		return serverPath;
	}
	
	
	
}
		

